package com.kuaimacode.kframework.api.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kuaimacode.kframework.api.service.category.AgentServService;
import com.kuaimacode.kframework.api.vo.AppMenuVO;
import com.kuaimacode.kframework.common.Constant;
import com.kuaimacode.kframework.mybatis.mapper.index.AppMenuMapper;
import com.kuaimacode.kframework.mybatis.models.agent.SysAgent;
import com.kuaimacode.kframework.mybatis.models.category.AgentServ;
import com.kuaimacode.kframework.mybatis.models.index.AppMenu;
import com.kuaimacode.kframework.mybatis.models.sysparam.SysParam;
import com.kuaimacode.kframework.util.DictUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author qinyong
 * @Title:
 * @Package com.kuaimacode.kframework.api.service
 * @Description: created by IntelliJ IDEA
 * @date 2019-03-16 09:29
 */
@Service
public class AppMenuService extends ServiceImpl<AppMenuMapper, AppMenu> {

    @Autowired
    private AgentServService agentServiceService;
    @Autowired
    private AgentService agentService;

    @Autowired
    private SysParamService sysParamService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * app菜单根节点
     */
    private static final AppMenuVO APP_ROOT_MENU = new AppMenuVO();
    {
        APP_ROOT_MENU.setId("0");
        APP_ROOT_MENU.setName("根节点");
        APP_ROOT_MENU.setSort(0);
        APP_ROOT_MENU.setChild(new ArrayList<>());
    }

    /**
     * 获取首页头部菜单
     * @return
     */
    public List<AppMenuVO> getIndexMenu(String agentId) {
        QueryWrapper<AppMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_valid", 1);
        queryWrapper.orderByAsc("sort");
        List<AppMenu> menuList = new ArrayList<>();
        //一级菜单
        Map<String,String> map = DictUtil.keyValueList("SERVICE_CLASS");
        if(map!=null){
            for(String key:map.keySet()){
                AppMenu appMenu = new AppMenu();
                appMenu.setId(key);
                appMenu.setParentId(APP_ROOT_MENU.getId().toString());
                appMenu.setSort(Integer.parseInt(key));
                appMenu.setName(map.get(key));
                Map<String,String> subTypeMap = DictUtil.keyValueByPCodeList("SERVICE_CLASS",key);
                if(subTypeMap!=null){
                    for(String subKey:subTypeMap.keySet()){
                        AppMenu appMenu1 = new AppMenu();
                        appMenu1.setId(subKey);
                        appMenu1.setParentId(key);
                        appMenu1.setSort(Integer.parseInt(subKey));
                        appMenu1.setName(subTypeMap.get(subKey));
                        menuList.add(appMenu1);
                    }
                }
                menuList.add(appMenu);
            }
        }


        if (CollectionUtils.isNotEmpty(menuList)) {
            //构建菜单
            buildMenu(APP_ROOT_MENU, menuList);
        }
        return APP_ROOT_MENU.getChild();
    }

    /**
     * 返回 跑腿和分站开通的菜单
     */
    public List<AppMenuVO> getMenu(String agentId){

        List<AppMenu> menuList = new ArrayList<>();
        //跑腿分类必须显示
        AppMenu appMenu = new AppMenu();
        appMenu.setId(Constant.OrderTypeEnum.PAO_TUI.getCode().toString());
        appMenu.setCode(Constant.OrderTypeEnum.PAO_TUI.getCode().toString());
        appMenu.setParentId(APP_ROOT_MENU.getId().toString());
        appMenu.setSort(Constant.OrderTypeEnum.PAO_TUI.getCode());
        appMenu.setName(Constant.OrderTypeEnum.PAO_TUI.getMessage().toString());
        Map<String,String> subTypeMap = DictUtil.keyValueByPCodeList(Constant.SERVICE_CLASS_DICT_NAME,Constant.OrderTypeEnum.PAO_TUI.getCode().toString());
        //查询总后台设置'是否显示叫外卖功能'
//        SysParam sysParam = sysParamService.findByName("IS_SHOW_WAIMAI");
        SysAgent sysAgent = agentService.getById(agentId);
        if(subTypeMap!=null){
            for(String subKey:subTypeMap.keySet()){
                //如果开关为关闭，不再显示
                if(sysAgent!=null&&sysAgent.getTakeawayStat()!=1 && Constant.WAIMAI.equals(subTypeMap.get(subKey))) continue;
                AppMenu appMenu1 = new AppMenu();
                appMenu1.setId(subKey);
                appMenu1.setCode(subKey);
                appMenu1.setParentId(Constant.OrderTypeEnum.PAO_TUI.getCode().toString());
                appMenu1.setSort(Integer.parseInt(subKey));
                appMenu1.setName(subTypeMap.get(subKey));
                menuList.add(appMenu1);
            }
        }
        menuList.add(appMenu);
        //再去查询分站开通的特色服务
        List<AgentServ> serviceList = agentServiceService.queryServByAgentId(agentId);
        List<String> serviceClassList = new ArrayList<>();
        for(AgentServ service:serviceList){
            if(!serviceClassList.contains(service.getServiceClass())){//如果list里不包含该serviceClass ， 创建该serviceClass menu
                String className = DictUtil.keyValue(Constant.SERVICE_CLASS_DICT_NAME,service.getServiceClass());
                AppMenu appM = new AppMenu();
                appM.setId(service.getServiceClass());
                appM.setCode(service.getServiceClass());
                appM.setParentId(APP_ROOT_MENU.getId().toString());
                appM.setSort(Integer.parseInt(service.getServiceClass()));
                appM.setName(className);
                menuList.add(appM);

                serviceClassList.add(service.getServiceClass());
            }
            //查询该二级分类名称
            String serviceName = DictUtil.keyValue(Constant.SERVICE_CLASS_DICT_NAME+"_"+service.getServiceClass(),service.getServiceCode());
            AppMenu appM1 = new AppMenu();
            appM1.setId(service.getId()+"");
            appM1.setCode(service.getServiceCode());
            appM1.setParentId(service.getServiceClass());
            appM1.setSort(Integer.parseInt(service.getServiceCode()));
            appM1.setName(serviceName);
            menuList.add(appM1);

        }

        if (CollectionUtils.isNotEmpty(menuList)) {
            //构建菜单
            buildMenu(APP_ROOT_MENU, menuList);
        }
        return APP_ROOT_MENU.getChild();

    }


    /**
     * 构建菜单树
     * @param root
     * @param menuList
     */
    private void buildMenu(AppMenuVO root, List<AppMenu> menuList) {
        List<AppMenuVO> child = new ArrayList<>();
        menuList.forEach(appMenu -> {
            if (root.getId().equals(appMenu.getParentId())) {
                AppMenuVO menuVO = new AppMenuVO();
                BeanUtils.copyProperties(appMenu, menuVO);
                child.add(menuVO);
            }
        });

        root.setChild(child);
        if (child.isEmpty()) {
            return;
        }
        child.forEach(appMenuVO -> buildMenu(appMenuVO, menuList));
    }
}
